package com.mymoney.persistence.managers;

import java.util.List;

import com.mymoney.beans.CategoryBean;
import com.mymoney.exceptions.MyMoneyException;
import com.mymoney.persistence.PersistenceContext;


public class CategoryManager extends AbstractBeanManager<CategoryBean> {


	public CategoryManager(PersistenceContext persistenceContext) {
		super(persistenceContext);
	}

	
	@Override
	public CategoryBean getByCode(long code) {

		return getBy("select p from CategoryBean p where p.code = :code", code, "code");
	}
	
	
	@Override
	public CategoryBean getByName(String name) {

		return getBy("select p from CategoryBean p where p.name = :name", name, "name");
	}
	

	@Override
	public CategoryBean getById(Integer id) throws MyMoneyException {
		
		return getBy("select p from CategoryBean p where p.id = :id", id, "id");
	}


	@Override
	public List<CategoryBean> list() {

		String queryString = "select s from CategoryBean s";
		List<CategoryBean> categories = findAllEntities(queryString, -1,(Object[]) null);
		return categories;
	}


	@Override
	public void add(CategoryBean category) throws MyMoneyException {
		if(category != null)
		{
			CategoryBean existingCategory = getByName(category.getName());
			if(existingCategory == null)
			{
				category.setCode(System.currentTimeMillis());
				storeEntity(category);
			}
			else
			{
				category.setCode(existingCategory.getCode());
			}
		}
		else
		{
			throw new MyMoneyException("The category is not initialized.");
		}
	}


	@Override
	public void update(CategoryBean category, CategoryBean existingCategory)
			throws MyMoneyException {

		if(category != null && existingCategory != null)
		{
			if(category.getName() != null)
			{
				existingCategory.setName(category.getName());
			}
			
			existingCategory.setCode(category.getCode());
			category.setId(existingCategory.getId());
		}
		else
		{
			throw new MyMoneyException("The category is not initialized");
		}
		
	}


	@Override
	public void update(CategoryBean category, long code)
			throws MyMoneyException {
		
		if(category != null)
		{
			CategoryBean existingCategory = getByCode(code);
			update(category, existingCategory);
		}
		
	}


	@Override
	public void update(CategoryBean category, Integer id)
			throws MyMoneyException {
		
		if(category != null)
		{
			CategoryBean existingCategory = getById(id);
			update(category, existingCategory);
		}
		
	}


	@Override
	public void update(CategoryBean category, String name)
			throws MyMoneyException {
		
		if(category != null)
		{
			CategoryBean existingCategory = getByName(name);
			update(category, existingCategory);
		}
		
	}
}